//
//  LSReadQuesView.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/8/30.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSReadQuesView.h"
#import "BKAudioPlayer.h"
#import "KZShadowButton.h"
#import "TYAttributedLabel.h"
#import "KZWaveRecordingView.h"
#import "KZAudioPlayOrRecordView.h"
#import "KYTestEngine.h"
#import "LSGetZSDManager.h"
#import "LSSaveZSDManager.h"
#import "DicMainView.h"
#import "LSGetTextDivideInfoManager.h"
#import "XYVoiceConverter.h"
#import "WJTimeCircle.h"

//static NSInteger tipHeight = 200;
//static NSInteger bottomY = 200;
//static NSInteger topY = -100;

@interface LSReadQuesView()<BKAudioPlayerDelegate,LSTYAttributedLabelDelegate,DicMainViewDelegate> {
    NSInteger tipHeight;
    NSInteger bottomY;
}

@property (nonatomic,strong) BKAudioPlayer *player;
/*标题栏*/
@property (nonatomic,strong) UIView *titleBarView;
/*分句模式label*/
@property (nonatomic,strong) UILabel *modeLabel;
/*定时器*/
@property (nonatomic,strong) NSTimer *timer;
/*时间*/
@property (nonatomic,assign) CGFloat second;
/*指示灯*/
@property (nonatomic,strong) UIView *indicatorView;
/*文本背景的scrollView*/
@property (nonatomic,strong) UIScrollView *scrollView;
/*段落*/
@property (nonatomic,strong) LSTYAttributedLabel *contentLabel;
/*知识点分析Label*/
@property (nonatomic,strong) LSTYAttributedLabel *zsdLabel;
/*段落文本*/
@property (nonatomic,strong) NSMutableAttributedString *attr;
/*录音/原音播放视图*/
@property (nonatomic,strong) UIView *playRecordView;
/*操作提示视图*/
@property (nonatomic,strong) UIView *tipsView;
/*提示文字*/
@property (nonatomic,strong) UILabel *tipLabel;
/*是否重新作答过*/
//@property (nonatomic,assign) BOOL isReAnswer;
/*录音按钮*/
@property (nonatomic,strong) KZWaveRecordingView *recordView;
/*声波视图*/
@property (nonatomic,strong) KZAudioPlayOrRecordView *volumeView;
/*正在评判*/
@property (nonatomic,strong) UIImageView * evaluatingView;
/*结果*/
@property (nonatomic,strong) UILabel *resultLabel;
/*重新朗读*/
@property (nonatomic,strong) UIButton *reReadBtn;
/*分句朗读*/
@property (nonatomic,strong) KZShadowButton *senReadBtn;
/*下一题*/
@property (nonatomic,strong) KZShadowButton *nextBtn;
/*我的录音*/
@property (nonatomic,strong) UIButton *myRecordBtn;
/*参考录音*/
@property (nonatomic,strong) UIButton *trueRecordBtn;
/*是否分句*/
@property (nonatomic,assign) BOOL isSenRead;
/*分句数组*/
@property (nonatomic,strong) NSMutableArray *senArr;
/*分句label数组*/
@property (nonatomic,strong) NSMutableArray *senLabelArr;
/*分句前结果*/
@property (nonatomic,copy) NSString *beforeSenResult;
/**/
@property (nonatomic,copy) NSString *testResult;
/*播放速度*/
@property (nonatomic,assign) CGFloat playRate;
/*段落的录音路径*/
@property (nonatomic,copy) NSString *pWavPath;

@property (nonatomic,strong) DicMainView *dictView;

@property (nonatomic,assign) CGFloat readRate;
/*最后一题按钮显示*/
@property (nonatomic,assign) BOOL isNoMore;

@property (nonatomic,strong) NSMutableArray *mutlCodeArr;
@property (nonatomic,strong) NSMutableArray *mutlNameArr;

/*倒计时*/
@property (nonatomic,strong) WJTimeCircle *timeCircleView;


@end

@implementation LSReadQuesView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        //self.backgroundColor = [UIColor redColor];
        self.player = [[BKAudioPlayer alloc] init];
        self.player.delegateM = self;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeReleaseAction) name:@"TimeRelease" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimePauseAction) name:@"TimePause" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeResumeAction) name:@"TimeResume" object:nil];
        
    }
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        //self.backgroundColor = [UIColor redColor];
        self.player = [[BKAudioPlayer alloc] init];
        self.player.delegateM = self;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeReleaseAction) name:@"TimeRelease" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimePauseAction) name:@"TimePause" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeResumeAction) name:@"TimeResume" object:nil];
        
    }
    return self;
}

- (void)setModel:(LSModelQues *)model {
    _model = model;
    
   // self.isReAnswer = YES;
    
    tipHeight = 200;
    bottomY = 200;
    
    if (self.speedLayer==1) {
        _playRate = 0.8;
        _readRate = LS_System.lowSpeed;
    } else if (self.speedLayer==2) {
        _playRate = 1.0;
        _readRate = LS_System.normalSpeed;

    } else if (self.speedLayer==3) {
        _playRate = 1.2;
        _readRate = LS_System.highSpeed;
    }
    
    [self createUI];
}

- (void)createUI {
    [self addSubview:self.titleBarView];
    [self.titleBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self);
        make.height.mas_equalTo(35);
    }];
    
    [self addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.top.equalTo(self).offset(70);
        make.height.mas_equalTo(kHeight-kNavgationBar-kBottomPadding-tipHeight-70);
    }];
    
    [self addSubview:self.tipsView];
    [self.tipsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.mas_equalTo(tipHeight);
    }];
    
    [self.tipsView addSubview:self.tipLabel];

    if (self.answerState==2) {
        
        [self addSubview:self.trueRecordBtn];
        self.trueRecordBtn.x = kWidth-10-80;
        
    } else {
        
        [self startTimeCircle];
        
    }
}

//开始倒计时
- (void)startTimeCircle {
    self.pasueState = 1;
    self.second = self.model.ReadTime;

    [self.tipsView addSubview:self.timeCircleView];
    self.timeCircleView.totalSecond = self.second;
    
    self.tipLabel.y = bottomY + tipHeight;
    self.tipLabel.text = @"请浏览试题,倒计时结束后开始准备训练\n(点击可提前结束浏览时间)";
    self.tipLabel.height = 30;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.timeCircleView.y=5;
        self.tipLabel.y = self.timeCircleView.y+5+self.timeCircleView.height;
        
    } completion:^(BOOL finished) {
        
    }];
    
    if(self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timeAnim) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)timeAnim{
    self.second = self.second-0.01;
    //NSLog(@"===%f",self.second);
    if (self.second <= 0.00) {
        [self timeCircleEnd];
    } else {
        self.timeCircleView.second = self.second;
    }
}

- (void)timeCircleEnd {
    [self.timer invalidate];
    self.timer = nil;
    
    self.timeCircleView.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        self.timeCircleView.y = bottomY+tipHeight;
        self.tipLabel.y = bottomY+tipHeight;
        
    } completion:^(BOOL finished) {
        [self.timeCircleView removeFromSuperview];
        self.timeCircleView = nil;
    }];
    
    [self showIndicatorView];
}

- (void)showIndicatorView {
    
    if(self.isReAnswer) {
        self.pasueState = 2;
    } else {
        self.pasueState = 0;
    }
    
    self.tipLabel.text = @"请在指示灯全部消失后,开始朗读...";
    
    [self addSubview:self.indicatorView];
    [self.indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleBarView.mas_bottom);
        make.left.equalTo(self).offset(-100);
        make.size.mas_equalTo(CGSizeMake(80, 35));
    }];
    
    self.second = 0;
    if(self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(indicatorViewEnd) userInfo:nil repeats:YES];
     [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        self.tipLabel.y = (tipHeight-12)/2;
        
        [self.indicatorView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self);
        }];
        [self layoutIfNeeded];
        
        
    } completion:^(BOOL finished) {
        
    }];

}

#pragma mark - 懒加载

/*倒计时*/
- (WJTimeCircle *)timeCircleView {
    if (!_timeCircleView) {
        //_timeCircleView = [[WJTimeCircle alloc] initWithFrame:CGRectMake((kWidth-73)/2,_topY,73, 73)];
        _timeCircleView = [[WJTimeCircle alloc] initWithFrame:CGRectMake((kWidth-73)/2,bottomY+tipHeight,73, 73)];
        _timeCircleView.arcFinishColor = [UIColor colorWithHex:0xededed];
        _timeCircleView.arcUnfinishColor = [UIColor colorWithHex:0x50c6f9];
        _timeCircleView.arcBackColor = [UIColor clearColor];
        _timeCircleView.baseColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1];
        _timeCircleView.width = 3;
        _timeCircleView.isStartDisplay = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(timeCircleEnd)];
        [_timeCircleView addGestureRecognizer:tap];
        _timeCircleView.userInteractionEnabled = YES;
    }
    return _timeCircleView;
}

/*标题栏*/
- (UIView *)titleBarView {
    if (!_titleBarView) {
        _titleBarView = [[UIView alloc] init];
        UILabel *label = [[UILabel alloc] init];
        [_titleBarView addSubview:label];
        label.font = FONT(13);
        label.textColor = [UIColor colorWithHex:0x333333];
        NSString *text = [NSString stringWithFormat:@"第%ld题(共%ld题)",self.currentIndex+1,self.allCount];
        
        if (self.answerState==2) {
            text = @"朗读短文";
        }
        
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
        NSRange range = [text rangeOfString:[NSString stringWithFormat:@"第%ld题",self.currentIndex+1]];
        
        if (self.answerState==2) {
            range = NSMakeRange(0, text.length);
        }
        
        [attr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0x0693c8] range:range];
        label.attributedText = attr;
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_titleBarView).offset(11);
            make.centerY.equalTo(_titleBarView);
            make.size.mas_offset(CGSizeMake(100, 13));
        }];
        
        UILabel *line = [[UILabel alloc] init];
        line.backgroundColor = [UIColor colorWithHex:0xededed];
        [_titleBarView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(_titleBarView);
            make.bottom.equalTo(_titleBarView).offset(-0.5);
            make.height.mas_equalTo(0.5);
        }];
        
        UILabel *modeLabel = [[UILabel alloc] init];
        self.modeLabel = modeLabel;
        modeLabel.alpha = 0;
        modeLabel.text = @"分句朗读模式";
        modeLabel.font = FONT(13);
        modeLabel.textAlignment = NSTextAlignmentCenter;
        modeLabel.layer.cornerRadius = 3;
        modeLabel.layer.borderWidth = 1;
        modeLabel.layer.masksToBounds = YES;
        modeLabel.layer.borderColor = [UIColor colorWithHex:0x21A3FA].CGColor;
        modeLabel.textColor = [UIColor colorWithHex:0x21A3FA];
        [_titleBarView addSubview:modeLabel];
        [modeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(label.mas_right).offset(5);
            make.centerY.equalTo(_titleBarView);
            make.size.mas_offset(CGSizeMake(90, 22));
        }];
    }
    return _titleBarView;
}

- (UIView*)indicatorView {
    
    if (!_indicatorView) {
        
        _indicatorView = [[UIView alloc] init];
        _indicatorView.backgroundColor = [UIColor clearColor];
        for (NSInteger i = 0; i<4; i++) {
            UIImageView *imageView = [[UIImageView alloc] init];
            [_indicatorView addSubview:imageView];
            imageView.tag = 1003-i;
            imageView.alpha = 1;
            imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"LS-指示灯%ld",i+1]];
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_indicatorView).offset(12+i*16);
                make.centerY.equalTo(_indicatorView);
                make.size.mas_equalTo(CGSizeMake(10, 10));
            }];
        }
    }
    
    return _indicatorView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.backgroundColor = [UIColor whiteColor];
        NSString *content = self.model.ChildList.firstObject.ChildAnswer;
        if (content==nil || [content isEqualToString:@""]) {
            NSAttributedString *attributedText = [self.model.QuesBody dr_HtmlStringWithFontSize:15];
            self.attr = [[NSMutableAttributedString alloc] initWithAttributedString:attributedText];
        } else {
            self.attr = [[NSMutableAttributedString alloc] initWithAttributedString:[content dr_HtmlStringWithFontSize:15]];
        }

        self.contentLabel = [[LSTYAttributedLabel alloc] init];
        self.contentLabel.backgroundColor = [UIColor whiteColor];
        self.contentLabel.delegate = self;
        [_scrollView addSubview:self.contentLabel];
        self.contentLabel.attributedText = self.attr;
        self.contentLabel.numberOfLines = 0;
        self.contentLabel.linesSpacing = 5;
        self.contentLabel.lineBreakMode = NSLineBreakByWordWrapping;
        [self.contentLabel sizeToFit];
        CGFloat height = [self.contentLabel getSizeWithWidth:kWidth-20].height;
        _scrollView.contentSize = CGSizeMake(0, height+10);
        self.contentLabel.frame = CGRectMake(10,0, kWidth-20, height+2);
            
    }
    
    return _scrollView;
}

- (UIView *)playRecordView {
    if (!_playRecordView) {
        _playRecordView = [[UIView alloc] init];
    }
    return _playRecordView;
}

- (UIView*)tipsView {
    if (!_tipsView) {
        _tipsView = [[UIView alloc] init];
        //_tipsView.backgroundColor = [UIColor redColor];
    }
    
    return _tipsView;
}

- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(40,tipHeight+bottomY,kWidth-80, 12)];
        _tipLabel.textColor = [UIColor colorWithHex:0x4a4a4a];
        _tipLabel.font = [UIFont systemFontOfSize:11];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.numberOfLines = 0;
    }
    return _tipLabel;
}

- (KZWaveRecordingView *)recordView {
    if (!_recordView) {
        _recordView = [[KZWaveRecordingView alloc] init];
        _recordView.frame = CGRectMake((kWidth-70)/2,tipHeight+bottomY, 70, 70);
    }
    return _recordView;
}

- (KZAudioPlayOrRecordView *)volumeView {
    if (!_volumeView) {
        _volumeView = [[KZAudioPlayOrRecordView alloc] init];
        _volumeView.frame = CGRectMake((kWidth-138)/2, tipHeight+bottomY, 138, 20);
    }
    return _volumeView;
}

- (UIImageView *)evaluatingView {
    if (!_evaluatingView) {
        _evaluatingView = [[UIImageView alloc] init];
        _evaluatingView.frame = CGRectMake((kWidth-70)/2,tipHeight+bottomY, 70, 70);
    }
    return _evaluatingView;
}

- (UILabel *)resultLabel {
    if (!_resultLabel) {
        _resultLabel = [[UILabel alloc] init];
        _resultLabel.frame =  CGRectMake((kWidth-70)/2,tipHeight+bottomY, 70, 70);
        _resultLabel.layer.cornerRadius = 35;
        _resultLabel.layer.masksToBounds = YES;
        _resultLabel.backgroundColor = [UIColor colorWithHex:0xea4f0c];
        _resultLabel.textAlignment = NSTextAlignmentCenter;
        _resultLabel.textColor = [UIColor whiteColor];
    }
    return _resultLabel;
}

- (UIButton *)reReadBtn {
    if (!_reReadBtn) {
        CGFloat WIDTH = 140;
        if (iPhone5S) {
            WIDTH = 94;
        }
        _reReadBtn = [[UIButton alloc] init];
        _reReadBtn.frame = CGRectMake((kWidth-WIDTH-94-94-10-10)/2, tipHeight+bottomY,94, 44);
        _reReadBtn.titleLabel.font = FONT(14);
        _reReadBtn.layer.cornerRadius = 6;
        _reReadBtn.layer.masksToBounds = YES;
        _reReadBtn.layer.borderWidth = 1.0f;
        _reReadBtn.layer.borderColor = [UIColor colorWithHex:0x19cdc7].CGColor;
        [_reReadBtn setTitleColor:[UIColor colorWithHex:0x19cdc7] forState:UIControlStateNormal];
        [_reReadBtn setTitle:@"重新朗读" forState:UIControlStateNormal];
        [_reReadBtn addTarget:self action:@selector(reAnswerAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _reReadBtn;
}

- (KZShadowButton *)senReadBtn {
    if (!_senReadBtn) {
        _senReadBtn = [[KZShadowButton alloc] init:^(UIButton *button) {
            button.backgroundColor = [UIColor colorWithHex:0x19cdc7];
            [button setTitle:@"分句朗读" forState:UIControlStateNormal];
            button.titleLabel.font = FONT(14);
        }];
        
        CGFloat WIDTH = 140;
        if (iPhone5S) {
            WIDTH = 94;
        }
        _senReadBtn.frame = CGRectMake((kWidth-WIDTH)/2,tipHeight+bottomY,WIDTH, 44);
        [_senReadBtn addTarget:self action:@selector(senReadAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _senReadBtn;
}

- (KZShadowButton *)nextBtn {
    if (!_nextBtn) {
        _nextBtn = [[KZShadowButton alloc] init:^(UIButton *button) {
            button.backgroundColor = RGBA(11, 178, 242, 1);
            [button setTitle:@"下一题" forState:UIControlStateNormal];
            button.titleLabel.font = FONT(14);
            if (self.currentIndex+1 == self.allCount) {
                [button setTitle:@"查看结果" forState:UIControlStateNormal];
            }
        }];
        CGFloat WIDTH = 140;
        if (iPhone5S) {
            WIDTH = 94;
        }
        _nextBtn.frame = CGRectMake(kWidth-(kWidth-WIDTH-94-94-10-10)/2-94 , tipHeight+bottomY, 94, 44);
        [_nextBtn addTarget:self action:@selector(nextBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        if(_isNoMore) {
            [_nextBtn.button setTitle:@"没有更多" forState:UIControlStateNormal] ;
            _nextBtn.button.backgroundColor = [UIColor colorWithHex:0xe1e2e2];
            _nextBtn.enabled = NO;
        }
    }
    return _nextBtn;
}

- (UIButton *)myRecordBtn {
    if (!_myRecordBtn) {
//        CGFloat Y = [self.attr boundingRectWithSize:CGSizeMake(kWidth-20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height+80;
        CGFloat Y = [self.contentLabel getSizeWithWidth:kWidth-20].height+80;
        if (Y-80>kHeight-kNavgationBar-kBottomPadding-tipHeight) {
            Y = kHeight-kNavgationBar-kBottomPadding-tipHeight+10;
        }
        _myRecordBtn = [[UIButton alloc] init];
        _myRecordBtn.frame = CGRectMake(-80,Y, 80, 20);
        [_myRecordBtn setImage:[UIImage imageNamed:@"LS-我的录音图标"] forState:UIControlStateNormal];
        [_myRecordBtn setTitle:@"我的录音" forState:UIControlStateNormal];
        _myRecordBtn.imageEdgeInsets = UIEdgeInsetsMake(0,50, 0, -50);
        _myRecordBtn.titleEdgeInsets = UIEdgeInsetsMake(0,-25,0,25);
        _myRecordBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [_myRecordBtn setTitleColor:[UIColor colorWithHex:0x464646] forState:UIControlStateNormal];
        [_myRecordBtn addTarget:self action:@selector(myRecordPlayAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _myRecordBtn;
}

- (UIButton *)trueRecordBtn {
    if (!_trueRecordBtn) {
        _trueRecordBtn = [[UIButton alloc] init];
//        CGFloat Y = [self.attr boundingRectWithSize:CGSizeMake(kWidth-20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height+80;
        CGFloat Y = [self.contentLabel getSizeWithWidth:kWidth-20].height+80;
        if (Y-80>kHeight-kNavgationBar-kBottomPadding-tipHeight) {
            Y = kHeight-kNavgationBar-kBottomPadding-tipHeight;
        }
        _trueRecordBtn.frame = CGRectMake(kWidth,Y, 80, 20);
        [_trueRecordBtn setImage:[UIImage imageNamed:@"LS-参考示范图标"] forState:UIControlStateNormal];
        [_trueRecordBtn setTitle:@"参考示范" forState:UIControlStateNormal];
        [_trueRecordBtn setTitleColor:[UIColor colorWithHex:0x464646] forState:UIControlStateNormal];
//        button.imageEdgeInsets = UIEdgeInsetsMake(0, titleW, 0, -titleW)//设置图片位置
//        button.titleEdgeInsets = UIEdgeInsetsMake(0, -(imgW + titleImgMargin), 0, (imgW + titleImgMargin))
        _trueRecordBtn.imageEdgeInsets = UIEdgeInsetsMake(0,50,0,-50);
        _trueRecordBtn.titleEdgeInsets = UIEdgeInsetsMake(0,-25,0,25);
        _trueRecordBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [_trueRecordBtn addTarget:self action:@selector(trueRecordPlayAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _trueRecordBtn;
}

#pragma mark - 定时器相关方法
//指示灯倒计时
- (void)indicatorViewEnd {
    UIImageView *imageView = [_indicatorView viewWithTag:1000+(int)self.second];
    self.second = self.second + 1.0;
    imageView.alpha = 0;
    if (self.second==4.0) {
        [self.timer invalidate];
        self.timer = nil;
        
        [self.indicatorView removeFromSuperview];
        self.indicatorView = nil;
        
        self.second = 0;
        if(self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05f target:self selector:@selector(recordTestEnd) userInfo:nil repeats:YES];
         [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

        [self.tipsView addSubview:self.recordView];
        [self.tipsView addSubview:self.volumeView];
        [self.tipsView addSubview:self.tipLabel];
        self.tipLabel.text = @"请跟随文字高亮进度进行朗读...";
        self.recordView.y = 10;
        self.volumeView.y = 85;

        //配置评测参数
        KYTestConfig *config = [[KYTestConfig alloc] init];
        config.coreType = KYTestType_Paragraph;
        config.refText = self.attr.string;
        config.phonemeOption = KYPhonemeOption_KK;
        config.audioType = @"wav";
        config.sampleRate = 16000;
        config.sampleBytes = 2;
        config.soundIntensityEnable = NO;
        config.paragraph_need_word_score = YES;
        
        __weak typeof(self) weakSelf = self;
        [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
            weakSelf.testResult = testResult;
            NSLog(@"testResult=%@",testResult);
        }];
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.tipLabel.y = tipHeight+bottomY;
            
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.3 animations:^{
                
//                self.recordView.y = 10;
//                self.volumeView.y = 85;
                self.tipLabel.y = 115;
                
            } completion:^(BOOL finished) {
                
                
            }];
            
        }];
    }
}

//录音评测计时
- (void)recordTestEnd {
    CGFloat totalTime = [self.contentLabel.attributedText.string componentsSeparatedByString:@" "].count / _readRate;
   // NSLog(@"totalTime = %f",totalTime);
    self.second = self.second + 0.05;
    CGFloat len = (self.second/totalTime * self.contentLabel.attributedText.string.length);
    if (len >= self.contentLabel.attributedText.string.length) {
        len = self.contentLabel.attributedText.string.length;
    }
    NSRange range = NSMakeRange(0, len);
    [self.attr addAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor]} range:range];
    self.contentLabel.attributedText = self.attr;
    if (self.second>=totalTime+2) {
        
        if(self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
        self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(loadingEvaluatingView:) userInfo:nil repeats:NO];
         [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        
        //结束评测，返回结果
        [[KYTestEngine sharedInstance] stopEngine];
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.volumeView.y = tipHeight+bottomY;
            self.recordView.y = tipHeight+bottomY;
            self.tipLabel.y = tipHeight+bottomY;
            
        } completion:^(BOOL finished) {
            
            [self.recordView removeFromSuperview];
            self.recordView = nil;
            [self.volumeView removeFromSuperview];
            [self.volumeView freeSource];
            self.volumeView = nil;
            [self.tipLabel removeFromSuperview];
            self.tipLabel = nil;
            
            [self.tipsView addSubview:self.evaluatingView];
            [self.evaluatingView gif:@"__4"];
            [self.tipsView addSubview:self.tipLabel];
            self.tipLabel.text = @"系统正在给您评判,请稍等...";
            [UIView animateWithDuration:0.3 animations:^{
                
                self.evaluatingView.y = 10;
                self.tipLabel.y = 85;
                
            } completion:^(BOOL finished) {
                

            }];

        
        }];
    }
}

//加载评测结果动画
- (void)loadingEvaluatingView:(NSTimer*)time {
    
    if(self.testResult==nil) {
        if(self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
        self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(delayShowResult) userInfo:nil repeats:NO];
         [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    } else {
        
        [self delayShowResult];
        
    }
}

- (void)delayShowResult {
    
    [self.timer invalidate];
    self.timer = nil;
    
    self.tipLabel.y = bottomY+tipHeight;
    [self.tipLabel removeFromSuperview];
    self.tipLabel = nil;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.evaluatingView.y = bottomY+tipHeight;
        
    } completion:^(BOOL finished) {
        
        [self.evaluatingView removeFromSuperview];
        
        self.evaluatingView = nil;
        
    }];
    //结束评测，返回结果
    [self showResult:self.testResult];
}


#pragma mark - 解析评测结果
- (void)showResult:(NSString *)result {
    // printf("%s\n", [result UTF8String]);
    self.pasueState = 1;
    self.answerState = 1;

        NSString *wavPath = [KYTestEngine sharedInstance].currentWavPath;
        NSLog(@"wavPath=%@",wavPath);
        self.pWavPath = wavPath;
        
        if([result rangeOfString:@"errId"].length > 0) {  //错误回调
            
            NSLog(@"result：%@",result);
            [MBProgressHUD showOnlyText:@"口语评测错误" position:KZHUDPositionModeCenter duration:3];
            
        } else if ([result rangeOfString:@"sound_intensity"].length > 0) {  //音强回调
            
            NSError *error;
            NSData *rdata = [result dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
            CGFloat soundIntensity = [[resultDic objectForKey:@"sound_intensity"] floatValue];
            NSLog(@"音量：%f",soundIntensity/100.0f);
            
        } else {
            NSError *error;
            
            if (result == nil) {
                result = @"{\"result\" : {\"overall\" : 0}}";
            }
            NSData *rdata = [result dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
            NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
            NSString *str = [NSString stringWithFormat:@"%@",[jsonresult objectForKey:@"overall"]];
            self.beforeSenResult = result;
            NSLog(@"评测结果:%@",str);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //保存回调
                if (self.isReAnswer==NO) {
                    if (self.delegate && [self.delegate respondsToSelector:@selector(FinishAnswerWordDict:IsSave:)]) {
                        [self.delegate FinishAnswerWordDict:resultDic IsSave:NO];
                    }
                }
                
                [self.tipsView addSubview:self.resultLabel];
                
                if (self.isReAnswer==NO) { //第一次作答错误
                    self.isReAnswer = YES;
                    [self.tipsView addSubview:self.tipLabel];
                    
                    self.second = 3.0f;
                    if (str.integerValue>=LS_System.readScore) {//合格自动进入下一题
                        if(self.timer) {
                            [self.timer invalidate];
                            self.timer = nil;
                        }
                        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(enterNextQues) userInfo:nil repeats:YES];
                         [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
                    }
                    else {
                        if(self.timer) {
                            [self.timer invalidate];
                            self.timer = nil;
                        }
                        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(reAnswerControl) userInfo:nil repeats:YES];
                         [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
                    }
                    
                    [UIView animateWithDuration:0.5 animations:^{
                        if (str.integerValue>=LS_System.readScore) {
                            self.resultLabel.text = @"合格";
                            self.resultLabel.backgroundColor = [UIColor colorWithHex:0x18ba2b];
                            self.resultLabel.y = 10;
                            self.tipLabel.y = 85;
                            
                            self.tipLabel.text = [NSString stringWithFormat:@"%d秒后进入下一题",(int)self.second];
                            if (self.currentIndex+1 == self.allCount) {
                                self.tipLabel.text = [NSString stringWithFormat:@"%d秒后进入查看结果",(int)self.second];
                                //代理回调
                                if(self.moudleID==2) {
                                    
                                    [self.timer invalidate];
                                    self.timer = nil;
                                    self.tipLabel.text = @"系统评判结果";
                                    
                                    if(self.delegate && [self.delegate respondsToSelector:@selector(retrunShowComplteView)]) {
                                        [self.delegate retrunShowComplteView];
                                    }
                                }
                            }
                            
                        } else {
                            self.resultLabel.text = @"不合格";
                            self.resultLabel.backgroundColor = [UIColor colorWithHex:0xea4f0c];
                            self.resultLabel.y = 10;
                            self.tipLabel.y = 85;
                            
                            self.tipLabel.text = [NSString stringWithFormat:@"重新朗读，请准备...%ds",(int)self.second];
                            
                        }
                    } completion:^(BOOL finished) {
                        
                    }];
                    
                } else {//非第一次错误
                    [self.tipsView addSubview:self.tipLabel];
                    self.tipLabel.text = @"系统评判结果";
                    
                    [self.tipsView addSubview:self.reReadBtn];
                    [self.tipsView addSubview:self.senReadBtn];
                    [self.tipsView addSubview:self.nextBtn];
                    
                    [self addSubview:self.trueRecordBtn];
                    [self addSubview:self.myRecordBtn];
                    
                    [UIView animateWithDuration:0.5 animations:^{
                        
                        self.myRecordBtn.x = 10;
                        self.trueRecordBtn.x = kWidth-10-80;
                        
                        if (str.integerValue>=LS_System.readScore) {
                            
                            self.resultLabel.text = @"合格";
                            self.resultLabel.backgroundColor = [UIColor colorWithHex:0x18ba2b];
                            self.resultLabel.y = 10;
                            self.tipLabel.y = 85;
                            
//                            self.nextBtn.y = tipHeight-44-20;
//                            self.nextBtn.centerX = self.tipsView.centerX;
                            self.reReadBtn.y = tipHeight-44-20;
                            self.senReadBtn.y = tipHeight-44-20;
                            self.nextBtn.y = tipHeight-44-20;
                            
                        } else {
                            
                            self.resultLabel.text = @"不合格";
                            self.resultLabel.backgroundColor = [UIColor colorWithHex:0xea4f0c];
                            self.resultLabel.y = 10;
                            self.tipLabel.y = 85;
                            
                            self.reReadBtn.y = tipHeight-44-20;
                            self.senReadBtn.y = tipHeight-44-20;
                            self.nextBtn.y = tipHeight-44-20;
                        }
                        
                    } completion:^(BOOL finished) {
                        
                        //错题最后一题回调
                        if (!self.isUseReAnswerBtn && (self.currentIndex+1 == self.allCount)) {
                            if(self.delegate && [self.delegate respondsToSelector:@selector(retrunShowComplteView)]) {
                                [self.delegate retrunShowComplteView];
                            }
                        }
                        
                        //调用知识点分析
                        if (self.isReAnswer) {
                            
                            NSString *testString = @"";
                            NSArray *senarr = jsonresult[@"sentences"];
                            for (NSInteger i = 0; i<senarr.count; i++) {
                                NSDictionary *sen = senarr[i];
                                NSArray *wordarr = sen[@"details"];
                                for (NSInteger j = 0; j<wordarr.count; j++) {
                                    NSDictionary *word = wordarr[j];
                                    NSNumber *num = word[@"overall"];
                                    if (num.integerValue<LS_System.readScore) {
                                        //去除首尾标点
                                        NSMutableCharacterSet *set = [[NSMutableCharacterSet alloc] init];
                                        [set formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];//标点
                                        NSString *wordstring = [word[@"word"] stringByTrimmingCharactersInSet:set];
                                        testString = [NSString stringWithFormat:@"%@ %@",testString,wordstring];
                                    }
                                }
                            }
                            NSLog(@"testString=%@",testString);
                            
                            self.zsdLabel = [[LSTYAttributedLabel alloc] initWithFrame:self.contentLabel.frame];
                            self.zsdLabel.backgroundColor = [UIColor whiteColor];
                            self.zsdLabel.attributedText = self.contentLabel.attributedText;
                            self.zsdLabel.textColor = [UIColor blackColor];
                            self.zsdLabel.delegate = self;
                            self.zsdLabel.isTextBackgroundColor = YES;
                            self.zsdLabel.textBackgroundColor = [UIColor orangeColor];
                            [self.scrollView addSubview:self.zsdLabel];
                            LSGetZSDManager *manager = [[LSGetZSDManager alloc] init];
                            manager.requestParam = @{@"Text":testString,
                                                     @"stageNo":KGetUserDefaults(@"TestLayer")
                                                     };
                            WeakObj(self);
                            [MBProgressHUD showDefaultToView:self.zsdLabel];
                            [manager requestWithCompltionSuccess:^(NSArray *zsdArr) {
                                
                                NSMutableArray *mutlCodeArr = [NSMutableArray array];
                                NSMutableArray *mutlNameArr = [NSMutableArray array];
                                for (LSModelZSD *zsd in zsdArr) {
                                    [mutlCodeArr addObject:zsd.ZSDCode];
                                    [mutlNameArr addObject:zsd.ZSDNameInText];
                                }
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [selfWeak setupLabel:self.zsdLabel HightlightlyString:self.zsdLabel.attributedText.string Words:mutlNameArr Codes:mutlCodeArr];
                                    [MBProgressHUD hideHUDForView:self.zsdLabel animated:YES];
                                });
                                
                            } failuer:^(NSString *error) {
                                
                            }];
                        }
                    }];
                }
            });
        }
}

- (void)getZSDHightly:(NSString*)text {
    LSGetZSDManager *manager = [[LSGetZSDManager alloc] init];
    manager.requestParam = @{@"Text":text,
                             @"stageNo":KGetUserDefaults(@"TestLayer")
                             };
    WeakObj(self);
    [manager requestWithCompltionSuccess:^(NSArray *zsdArr) {
        
        selfWeak.mutlCodeArr = [NSMutableArray array];
        selfWeak.mutlNameArr = [NSMutableArray array];
        for (LSModelZSD *zsd in zsdArr) {
            [selfWeak.mutlCodeArr addObject:zsd.ZSDCode];
            [selfWeak.mutlNameArr addObject:zsd.ZSDNameInText];
        }
        
    } failuer:^(NSString *error) {
        
    }];
}

#pragma mark - 重新作答流程
//自动进入下一题
- (void)enterNextQues {
    self.second = self.second-1.0;
    self.tipLabel.text = [NSString stringWithFormat:@"%ds后进入下一题",(int)self.second];
    if (self.currentIndex+1 == self.allCount) {
        self.tipLabel.text = [NSString stringWithFormat:@"%d秒后进入查看结果",(int)self.second];
    }
    if (self.second<=0.0) {
        [self.timer invalidate];
        self.timer = nil;
        if (self.delegate && [self.delegate respondsToSelector:@selector(willEnterNextQues)]) {
            [self.delegate willEnterNextQues];
        }
    }
}

- (void)reAnswerControl {
 
     [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    self.second = self.second-1.0;
    self.tipLabel.text = [NSString stringWithFormat:@"重新朗读，请准备...%ds",(int)self.second];
    
    if (self.second<=0.0) {
        
        [self.timer invalidate];
        self.timer = nil;
        
        [self.attr addAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(0, self.attr.length)];
        self.contentLabel.attributedText = self.attr;
         [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        
        [self startTimeCircle];
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.resultLabel.y = bottomY+tipHeight;
            
        } completion:^(BOOL finished) {
            
            [self.resultLabel removeFromSuperview];
            self.resultLabel = nil;
            
        }];
    }
}

#pragma mark - ButtonAction
- (void)senReadAction:(id)sender {
    _isSenRead = !_isSenRead;
   
    [self.timer invalidate];
    self.timer = nil;
    [self.player closePlayer];
    
    KZShadowButton *btn = (KZShadowButton*)sender;
    if (_isSenRead) {
        [btn.button setTitle:@"退出分句朗读" forState:UIControlStateNormal];
        self.modeLabel.alpha = 1;
        self.zsdLabel.alpha = 0;
        [self showSenReadView];
        self.answerState = 1;
        
    } else {
        [btn.button setTitle:@"分句朗读" forState:UIControlStateNormal];
        self.modeLabel.alpha = 0;
        self.zsdLabel.alpha = 1;
        self.answerState = 1;
        
        for (NSInteger i = 0; i<self.senLabelArr.count; i++) {
            TYAttributedLabel *label = self.senLabelArr[i];
            [label removeFromSuperview];
            label = nil;
        }
        
        self.contentLabel.attributedText = self.attr;
        [self.contentLabel sizeToFit];
        self.scrollView.contentSize = CGSizeMake(0, [self.contentLabel getSizeWithWidth:kWidth-20].height);
        if (self.contentLabel.height>kHeight-kNavgationBar-kBottomPadding-tipHeight-80) {
            self.myRecordBtn.y = kHeight-kNavgationBar-kBottomPadding-tipHeight+10;
            self.trueRecordBtn.y = kHeight-kNavgationBar-kBottomPadding-tipHeight+10;
        } else {
            self.myRecordBtn.y = 80+self.contentLabel.height;
            self.trueRecordBtn.y = 80+self.contentLabel.height;
        }
        
        NSData *rdata = [self.beforeSenResult dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:nil];
        NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
        NSString *str = [NSString stringWithFormat:@"%@",[jsonresult objectForKey:@"overall"]];
        if (str.integerValue>=LS_System.readScore) {
            self.resultLabel.text = @"合格";
            self.resultLabel.backgroundColor = [UIColor colorWithHex:0x18ba2b];
        } else {
            self.resultLabel.text = @"不合格";
            self.resultLabel.backgroundColor = [UIColor colorWithHex:0xea4f0c];
        }
    }
    
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)reAnswerAction:(id)sender {
    
    self.isUseReAnswerBtn = YES;
    
    self.pasueState = 2;
    self.modeLabel.alpha = 0;
    for (NSInteger i = 0; i<self.senLabelArr.count; i++) {
        TYAttributedLabel *label = self.senLabelArr[i];
        [label removeFromSuperview];
        label = nil;
    }
    
    [self.timer invalidate];
    self.timer = nil;
    [self.player closePlayer];

    [self.zsdLabel removeFromSuperview];
    self.zsdLabel = nil;
    self.zsdLabel.alpha = 1.0;
    
    [self.attr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,self.attr.length)];
    self.contentLabel.attributedText = self.attr;
    self.contentLabel.linesSpacing = 5;
    CGFloat height = [self.contentLabel getSizeWithWidth:kWidth-20].height;
    _scrollView.contentSize = CGSizeMake(0, height+10);
    [_scrollView scrollsToTop];
    
    [self startTimeCircle];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.resultLabel.y = bottomY+tipHeight;
       // self.tipLabel.y = bottomY+tipHeight;
        self.reReadBtn.y = bottomY+tipHeight;
        self.senReadBtn.y = bottomY+tipHeight;
        self.nextBtn.y = bottomY+tipHeight;
        self.myRecordBtn.x = -80;
        self.trueRecordBtn.x = kWidth;
        
    } completion:^(BOOL finished) {
        
        [self.resultLabel removeFromSuperview];
        self.resultLabel = nil;
        
//        [self.tipLabel removeFromSuperview];
//        self.tipLabel = nil;
        
        [self.reReadBtn removeFromSuperview];
        self.reReadBtn = nil;
        [self.senReadBtn removeFromSuperview];
        self.senReadBtn = nil;
        [self.nextBtn removeFromSuperview];
        self.nextBtn = nil;
        [self.myRecordBtn removeFromSuperview];
        self.myRecordBtn = nil;
        [self.trueRecordBtn removeFromSuperview];
        self.trueRecordBtn = nil;
        
        /*
        [self.tipsView addSubview:self.tipLabel];
        self.tipLabel.text = @"请在指示灯全部消失后,开始朗读...";
        [self addSubview:self.indicatorView];
        [self.indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.titleBarView.mas_bottom);
            make.left.equalTo(self).offset(-100);
            make.size.mas_equalTo(CGSizeMake(80, 35));
        }];*/
        
        //重新设置contentLabel
        /*
        [self.zsdLabel removeFromSuperview];
        self.zsdLabel = nil;
        self.zsdLabel.alpha = 1.0;
        
        [self.attr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,self.attr.length)];
        self.contentLabel.attributedText = self.attr;
        self.contentLabel.linesSpacing = 5;
        CGFloat height = [self.contentLabel getSizeWithWidth:kWidth-20].height;
        _scrollView.contentSize = CGSizeMake(0, height+10);
        [_scrollView scrollsToTop];*/
        //动画
        /*
        [UIView animateWithDuration:0.5 animations:^{
            
            self.tipLabel.y = (tipHeight-12)/2;
            
            [self.indicatorView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self);
            }];
            [self layoutIfNeeded];
            
            
        } completion:^(BOOL finished) {
            
          
        }];*/
        
    }];

}

- (void)nextBtnAction:(id)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(willEnterNextQues)]) {
        [self.delegate willEnterNextQues];
    }
}

- (void)myRecordPlayAction:(id)sender {
//    NSString *wavPath = [KYTestEngine sharedInstance].currentWavPath;
//    NSLog(@"wavPath=%@",wavPath);
  //  [[KYTestEngine sharedInstance] playback];
    NSURL *url = [NSURL fileURLWithPath:self.pWavPath];
    [self.player playerUrl:url seekTotime:0 rateValue:1.0];
}

- (void)trueRecordPlayAction:(id)sender {
    NSURL *url = [NSURL fileURLWithPath:self.model.AudioList.firstObject.AudioPath];
    if (_playRate == 0) {
        _playRate = 1;
    }
    [self.player playerUrl:url seekTotime:0 rateValue:_playRate];
  //  [MBProgressHUD showOnlyText:@"暂无参考录音" position:KZHUDPositionModeCenter duration:1];
}

#pragma mark - 分句界面
- (void)showSenReadView {
    self.contentLabel.attributedText = [NSAttributedString new];
    self.senArr = [NSMutableArray array];
    LSGetTextDivideInfoManager *manager = [[LSGetTextDivideInfoManager alloc] init];
    manager.requestParam = @{@"Text":self.attr.string};
    [manager requestWithCompltionSuccess:^(NSArray *senarray) {
        for (LSTextDivide *model in senarray) {
            [self.senArr  addObject:model.Sentence];
        }
        [self showSenReadText];
        
    } failuer:^(NSString *error) {
        
    }];
    /*
//    NSString *text = [NSString stringWithFormat:@"%@ ",self.attr.string];
//    [text enumerateSubstringsInRange:NSMakeRange(0, text.length-1) options:NSStringEnumerationBySentences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
//
//        [self.senArr addObject:substring];
//    }];
   
    NSData *rdata = [self.testResult dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:nil];
    NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
    NSArray *array = jsonresult[@"sentences"];
    for (NSInteger i = 0; i<array.count; i++) {
        NSDictionary *dict = array[i];
        [_senArr addObject:dict[@"sentence"]];
    }
      [self showSenReadText];
     */
 
}

- (void)showSenReadText {
    
    CGFloat Y = 0;
    self.senLabelArr = [NSMutableArray array];
    for (NSInteger i = 0; i<self.senArr.count; i++) {
        NSString *text = [NSString stringWithFormat:@"%ld.%@",i+1,self.senArr[i]];
        LSTYAttributedLabel *label = [[LSTYAttributedLabel alloc] init];
        label.delegate = self;
        label.tag = 3000+i;
        label.attributedText = [text dr_HtmlStringWithFontSize:15.0f];
        label.numberOfLines = 0;
        label.lineBreakMode = NSLineBreakByWordWrapping;
        [label addLinkWithLinkData:text linkColor:[UIColor blackColor] underLineStyle:kCTUnderlineStyleNone range:NSMakeRange(0, label.attributedText.length)];
        label.linesSpacing = 5;
        [label sizeToFit];
        CGFloat height = [label getSizeWithWidth:kWidth-20].height;
        label.frame = CGRectMake(10, Y, kWidth-20, height);
        Y = Y+height+10;
        [self.scrollView addSubview:label];
        [self.senLabelArr addObject:label];
    }
    self.scrollView.contentSize = CGSizeMake(0,Y);
    
    if ( Y > kHeight-kNavgationBar-kBottomPadding-tipHeight-80) {
        self.myRecordBtn.y = kHeight-kNavgationBar-kBottomPadding-tipHeight+10;
        self.trueRecordBtn.y = kHeight-kNavgationBar-kBottomPadding-tipHeight+10;
    } else {
        self.myRecordBtn.y = 80+ Y;
        self.trueRecordBtn.y = 80+ Y;
    }
}


#pragma mark - LSTYAttributedLabelDelegate
- (void)attributedLabel:(LSTYAttributedLabel *)attributedLabel textStorageClicked:(id<LSTYTextStorageProtocol>)TextRun atPoint:(CGPoint)point atRect:(CGRect)rect{
    attributedLabel.textColor = [UIColor blackColor];
    
    if ([TextRun isKindOfClass:[LSTYLinkTextStorage class]]) {
        
        if (_isSenRead) {
           // attributedLabel.linesSpacing = 5;
            [self.player playerPaused];
            [self.player closePlayer];
            
            self.second = 0;
            if(self.timer) {
                [self.timer invalidate];
                self.timer = nil;
            }
            self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(senRecordTest:) userInfo:attributedLabel repeats:YES];
             [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
            //配置评测参数
            KYTestConfig *config = [[KYTestConfig alloc] init];
            config.coreType = KYTestType_Sentence;
            config.refText = attributedLabel.attributedText.string;
            config.phonemeOption = KYPhonemeOption_KK;
            config.audioType = @"wav";
            config.sampleRate = 16000;
            config.sampleBytes = 2;
            config.soundIntensityEnable = NO;
            
            WeakObj(self);
            [[KYTestEngine sharedInstance] startEngineWithTestConfig:config result:^(NSString *testResult) {
                selfWeak.testResult = testResult;
            }];
            
            attributedLabel.textColor = [UIColor blackColor];
            
            self.scrollView.userInteractionEnabled = NO;
            
            [self.tipsView addSubview:self.recordView];
            [self.tipsView addSubview:self.volumeView];
            self.recordView.y = 10;
            self.volumeView.y = 85;
            
            [UIView animateWithDuration:0.3 animations:^{
                
                self.resultLabel.y = bottomY+tipHeight;
                self.tipLabel.y = bottomY + tipHeight;
                
                self.reReadBtn.y = bottomY+tipHeight;
                self.nextBtn.y = bottomY+tipHeight;
                self.senReadBtn.y = bottomY+tipHeight;
                self.myRecordBtn.x = -80;
                self.trueRecordBtn.x = kWidth;
                
            } completion:^(BOOL finished) {
                
                [self.resultLabel removeFromSuperview];
                self.resultLabel = nil;
                [self.tipLabel removeFromSuperview];
                self.tipLabel = nil;
                
//                [self.tipsView addSubview:self.recordView];
//                [self.tipsView addSubview:self.volumeView];
//                self.recordView.y = 10;
//                self.volumeView.y = 85;
                [self.tipsView addSubview:self.tipLabel];
                self.tipLabel.text = @"请跟随文字高亮进度进行朗读...";
                
                [UIView animateWithDuration:0.3 animations:^{
//                    self.recordView.y = 10;
//                    self.volumeView.y = 85;
                    self.tipLabel.y = 115;
                } completion:^(BOOL finished) {
                    
                }];
                
            }];
        } else {
            
            NSString *linkStr = ((TYLinkTextStorage*)TextRun).linkData;
            if (![linkStr isEqualToString:@""]) {
                
                //知识点课件显示及保存
                _dictView = [[DicMainView alloc] initWithTestType:DictTestType_Word isShowRecord:YES];
                _dictView.delegate = self;
                _dictView.dictUrl = [NSString stringWithFormat:@"%@api/ZXYYTS/W_ZXYYTS_GetCoursewareByCode",KGetUserDefaults(@"SystemIP")];
                _dictView.dictParam = @{
                                        @"knowledge":[linkStr componentsSeparatedByString:@"|"].firstObject,
                                        @"levelCode":KGetUserDefaults(@"TestLayer"),
                                        @"stageNo":KGetUserDefaults(@"TestLayer"),
                                        @"schoolId":DR_UserInfo.SchoolID,
                                        @"stuId":DR_UserInfo.UserID,
                                        };
                
                [_dictView popAnimated:YES];
                
                LSSaveZSDManager *manager = [[LSSaveZSDManager alloc] init];
                NSDictionary *dict = @{@"StageNo":KGetUserDefaults(@"TestLayer"),
                                       @"SchoolID":KGetUserDefaults(@"SchoolID"),
                                       @"StuID":DR_UserInfo.UserID,
                                       @"VocabularyID":[linkStr componentsSeparatedByString:@"|"].firstObject,
                                       @"Vocabulary":[linkStr componentsSeparatedByString:@"|"].lastObject,
                                       @"IsPassed":@0,
                                       @"ReviewPassedCount":@0,
                                       @"NeedReviewCount":@3,
                                       @"CreateTime":[NSDate date],
                                       @"UpdateTime":[NSDate date]
                                       };
                NSLog(@"%@",dict);
                manager.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                                         @"schoolId":DR_UserInfo.SchoolID,
                                         @"stuId":DR_UserInfo.UserID,
                                         @"ModelUnfamiliarVocabularyList":@[dict]
                                         };
                
                [manager requestSaveWithCompltionSuccess:^(NSString *string) {
                    NSLog(@"保存知识点");
                } failuer:^(NSString *error) {
                    
                }];
                
            }
            
        }
    }
}

#pragma mark - 分句下的录音测试
//录音
- (void)senRecordTest:(NSTimer*)time {

    self.pasueState = 3;
    
    LSTYAttributedLabel *label = (LSTYAttributedLabel*)time.userInfo;
    CGFloat totalTime = [label.attributedText.string componentsSeparatedByString:@" "].count / _readRate;
    self.second = self.second+0.05;

    CGFloat len = (self.second/totalTime * label.attributedText.length);
    if (len >= label.attributedText.length) {
        len = label.attributedText.length;
    }
    NSRange range = NSMakeRange(0, len);

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];//调整行间距
    long number = 0.5;
    CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);//
    NSMutableAttributedString *mutattr = [[NSMutableAttributedString alloc] initWithString:label.attributedText.string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0f],NSParagraphStyleAttributeName:paragraphStyle}];
    [mutattr addAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor]} range:range];
    [mutattr addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0,[mutattr length])];
    label.attributedText = mutattr;
    label.numberOfLines = 0;
    label.linesSpacing = 5;
    label.lineBreakMode = NSLineBreakByWordWrapping;

    [label sizeToFit];
    //label.font = [UIFont systemFontOfSize:1];
   
    if (self.second>=totalTime+2) {
        
        [label addLinkWithLinkData:label.attributedText.string linkColor:[UIColor orangeColor] underLineStyle:kCTUnderlineStyleNone range:NSMakeRange(0,label.attributedText.string.length)];
        
        if(self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
        self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(loadingEvaluatingView2:) userInfo:nil repeats:NO];
        
        [[KYTestEngine sharedInstance] stopEngine];
        
#pragma mark -       //音频剪切合并
        NSInteger insertStartTime = 0;
        NSInteger insertEndTime = 0;
        NSError *error;
        NSData *rdata = [self.beforeSenResult dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
        NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
        NSArray *senInfoArr = jsonresult[@"sentences"];
        NSMutableArray *thisSeninfoArr = [NSMutableArray array];
        for (NSInteger i = 0; i<senInfoArr.count; i++) {
            NSDictionary *dict = senInfoArr[i];
            NSString *string = dict[@"sentence"];
            if ([label.attributedText.string containsString:string]) {
                [thisSeninfoArr addObject:dict];
            }
        }
        
        //开始时间
        NSDictionary *startDict = thisSeninfoArr.firstObject;
        insertStartTime = ((NSNumber*)startDict[@"start"]).integerValue;
        if (insertStartTime==0) {
            NSRange range = [label.attributedText.string rangeOfString:[label.attributedText.string componentsSeparatedByString:@"."].firstObject];
            NSArray *array = [self.attr.string componentsSeparatedByString:[label.attributedText.string substringFromIndex:range.length+range.location+1]];
            insertStartTime = [array.firstObject componentsSeparatedByString:@" "].count / _readRate;
        }
       
        //结束时间
        NSDictionary *endDict = thisSeninfoArr.lastObject;
        insertEndTime = ((NSNumber*)endDict[@"end"]).integerValue;
        if (insertEndTime==0) {
            NSRange range = [label.attributedText.string rangeOfString:[label.attributedText.string componentsSeparatedByString:@"."].firstObject];
            NSArray *array = [self.attr.string componentsSeparatedByString:[label.attributedText.string substringFromIndex:range.length+range.location+1]];
            NSInteger startTime = [array.firstObject componentsSeparatedByString:@" "].count / _readRate;
            insertEndTime = startTime + [label.attributedText.string componentsSeparatedByString:@" "].count / _readRate;
        }
        NSLog(@"insertStartTime = %ld,insertEndTime = %ld",insertStartTime,insertEndTime);
        [[XYVoiceConverter alloc] xyConvert_audioCropOriginalPath:self.pWavPath insertPath:[KYTestEngine sharedInstance].currentWavPath insertStartTime:insertStartTime insertEndTime:insertEndTime saveID:@"111" isNeedMerge:YES];
        /*
        for (NSInteger i = 0; i<senInfoArr.count; i++) {
            NSDictionary *dict = senInfoArr[i];
            NSString *string = dict[@"sentence"];
            if ([label.attributedText.string containsString:string]) {
                
                NSInteger end = ((NSNumber*)dict[@"end"]).integerValue;
                if(end==0) {
                    NSRange range = [label.attributedText.string rangeOfString:[label.attributedText.string componentsSeparatedByString:@"."].firstObject];
                    NSArray *array = [self.attr.string componentsSeparatedByString:[label.attributedText.string substringFromIndex:range.length+range.location+1]];
                    insertStartTime = [array.firstObject componentsSeparatedByString:@" "].count / _readRate;
                    //insertEndTime = insertStartTime + [label.attributedText.string componentsSeparatedByString:@" "].count / _readRate;
                } else {
                    insertStartTime = ((NSNumber*)dict[@"start"]).integerValue/100;
                    //insertEndTime = ((NSNumber*)dict[@"end"]).integerValue/100;
                }
                
                NSLog(@"insertTime = %ld",insertStartTime);
//                [[XYVoiceConverter alloc] xyConvert_audioCropOriginalPath:self.pWavPath insertPath:[KYTestEngine sharedInstance].currentWavPath insertStartTime:insertStartTime insertEndTime:insertEndTime saveID:@"1111" isNeedMerge:YES];
                [[XYVoiceConverter alloc] xyConvert_audioCropOriginalPath:self.pWavPath insertPath:[KYTestEngine sharedInstance].currentWavPath insertTime:insertStartTime saveID:@"111" isNeedMerge:YES];
                break;
            }
        }*/
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.tipLabel.y = bottomY+tipHeight;
            self.recordView.y = bottomY+tipHeight;
            self.volumeView.y = bottomY+tipHeight;
            
        } completion:^(BOOL finished) {
            
            [self.tipLabel removeFromSuperview];
            self.tipLabel = nil;
            [self.recordView removeFromSuperview];
            self.recordView = nil;
            [self.volumeView removeFromSuperview];
            [self.volumeView freeSource];
            self.volumeView = nil;
            
            [self.tipsView addSubview: self.evaluatingView];
            [self.evaluatingView gif:@"__4"];
            [self.tipsView addSubview:self.tipLabel];
            self.tipLabel.text = @"系统正在给您评判,请稍候";
            [UIView animateWithDuration:0.3 animations:^{
                self.evaluatingView.y = 10;
                self.tipLabel.y = 85;
            } completion:^(BOOL finished) {

            }];
        }];
    }
}

//分析
- (void)loadingEvaluatingView2:(NSTimer*)time {
   // NSString *testResult = (NSString*)time.userInfo;
    [self.timer invalidate];
    self.timer = nil;
    
    self.tipLabel.y = bottomY+tipHeight;
    [self.tipLabel removeFromSuperview];
    self.tipLabel = nil;
    
    //结束评测，返回结果
    [self showSenResult:self.testResult];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.evaluatingView.y = bottomY+tipHeight;
        
    } completion:^(BOOL finished) {
        
        [self.evaluatingView removeFromSuperview];
        self.evaluatingView = nil;
        
    }];
    
}

//结果
- (void)showSenResult:(NSString*)result {
    
    self.pasueState = 1;

    self.scrollView.userInteractionEnabled = YES;
    
    if([result rangeOfString:@"errId"].length > 0) {  //错误回调
        
        NSLog(@"result：%@",result);
        [MBProgressHUD showOnlyText:@"口语评测错误" position:KZHUDPositionModeCenter duration:3];
        
    } else if ([result rangeOfString:@"sound_intensity"].length > 0) {  //音强回调
        NSError *error;
        NSData *rdata = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
        CGFloat soundIntensity = [[resultDic objectForKey:@"sound_intensity"] floatValue];
        NSLog(@"音量：%f",soundIntensity/100.0f);
        
    } else {
        NSError *error;
        NSData *rdata = [result dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:&error];
        NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
        NSString *str = [NSString stringWithFormat:@"%@",[jsonresult objectForKey:@"overall"]];
        NSLog(@"分句评测结果:%@",str);
        [UIView animateWithDuration:0.3 animations:^{
            
            self.evaluatingView.y = tipHeight+bottomY;
            self.tipLabel.y = tipHeight+bottomY;
            
        } completion:^(BOOL finished) {
            
            [self.evaluatingView removeFromSuperview];
            self.evaluatingView = nil;
            [self.tipLabel removeFromSuperview];
            self.tipLabel = nil;
            
            [self.tipsView addSubview:self.resultLabel];
            [self.tipsView addSubview:self.tipLabel];
            [UIView animateWithDuration:0.3 animations:^{
                
                self.nextBtn.y = tipHeight-44-20;
                self.senReadBtn.y = tipHeight - 44 - 20;
                self.reReadBtn.y = tipHeight - 44 -20;
                self.myRecordBtn.x = 10;
                self.trueRecordBtn.x = kWidth-10-80;
                
                if (str.integerValue>=LS_System.readScore) {
                    self.resultLabel.text = @"合格";
                    self.resultLabel.backgroundColor = [UIColor colorWithHex:0x18ba2b];
                    self.resultLabel.y = 10;
                    self.tipLabel.y = 85;
                    self.tipLabel.text = @"系统评判结果";
                    
                } else {
                    self.resultLabel.text = @"不合格";
                    self.resultLabel.backgroundColor = [UIColor colorWithHex:0xea4f0c];
                    self.resultLabel.y = 10;
                    self.tipLabel.y = 85;
                    self.tipLabel.text = @"系统评判结果";
                }
            }];
            
        }];
    }
}

#pragma mark - playerDelegate
- (void)audioUpdateWith:(float)time Totaltime:(float)totalTime {
    
}

- (void)audioPlayEnd {
    
}

#pragma mark - 取消定时器/暂停
- (void)TimeReleaseAction {
    NSLog(@"释放时间");
    [self.timer invalidate];
    self.timer = nil;
    [self.player closePlayer];
    [[KYTestEngine sharedInstance] cancelEngine];
    [self.volumeView freeSource];
}

- (void)TimePauseAction {
    [self.timer setFireDate:[NSDate distantFuture]];
    [self.volumeView pauseSource];
    [self.recordView pauseSource];
    [self.player playerPaused];
    [[KYTestEngine sharedInstance] pauseEngine];
}

- (void)TimeResumeAction {
    [self.timer setFireDate:[NSDate distantPast]];
    [self.volumeView beginSource];
    [self.recordView beginSource];
    [self.player playerPlay];
    [[KYTestEngine sharedInstance] resumeEngine];
}

#pragma mark - //**加载高亮**//
- (void)setupLabel:(LSTYAttributedLabel*)textLabel HightlightlyString:(NSString*)text Words:(NSArray*)words Codes:(NSArray*)codes{
    NSString *string = text;
    
    NSMutableArray *removeHadArr = [NSMutableArray array];
    [string enumerateSubstringsInRange:NSMakeRange(0, string.length-1) options:NSStringEnumerationByWords usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
        
        if([words containsObject:substring] && ![removeHadArr containsObject:substring]) {
            
            [removeHadArr addObject:substring];
            
            NSInteger index = [words indexOfObject:substring];
            //NSString *linkData = codes[index];
            NSString *linkData = [NSString stringWithFormat:@"%@|%@",codes[index],substring];
            [textLabel addLinkWithLinkData:linkData linkColor:[UIColor whiteColor] underLineStyle:kCTUnderlineStyleNone range:substringRange];
            //textLabel.linesSpacing = 10;
        }
    }];
    
}

#pragma mark - DicMainViewDelegate
- (void)colseDicMainView:(UIView *)dictView {
    [dictView removeFromSuperview];
    dictView = nil;
}

//分句时暂停
- (void)stratReAnswer {
    
    if (self.speedLayer==1) {
        _playRate = 0.8;
        _readRate = LS_System.lowSpeed;
    } else if (self.speedLayer==2) {
        _playRate = 1.0;
        _readRate = LS_System.normalSpeed;
        
    } else if (self.speedLayer==3) {
        _playRate = 1.2;
        _readRate = LS_System.highSpeed;
    }
    
    if (self.pasueState==0) {
        [self TimeReleaseAction];
        [self clearSubView];
        [self createUI];
    } else if (self.pasueState==2) {
        self.isReAnswer = YES;
        [self TimeReleaseAction];
        [self clearSubView];
        [self createUI];
    } else if (self.pasueState==3) {
        
        [self TimeReleaseAction];
        [self.recordView removeFromSuperview];
        self.recordView = nil;
        [self.volumeView removeFromSuperview];
        [self.volumeView freeSource];
        self.volumeView = nil;
        
        [self.tipsView addSubview:self.resultLabel];
        [self.tipsView addSubview:self.tipLabel];
        [UIView animateWithDuration:0.3 animations:^{
            
            self.nextBtn.y = tipHeight-44-20;
            self.senReadBtn.y = tipHeight - 44 - 20;
            self.reReadBtn.y = tipHeight - 44 -20;
            self.myRecordBtn.x = 10;
            self.trueRecordBtn.x = kWidth-10-80;
            
            NSData *rdata = [self.testResult dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:rdata options:NSJSONReadingMutableLeaves  error:nil];
            NSDictionary *jsonresult = [resultDic objectForKey:@"result"];
            NSString *str = [NSString stringWithFormat:@"%@",[jsonresult objectForKey:@"overall"]];
            if (str.integerValue>=LS_System.readScore) {
                self.resultLabel.text = @"合格";
                self.resultLabel.backgroundColor = [UIColor colorWithHex:0x18ba2b];
                self.resultLabel.y = 10;
                self.tipLabel.y = 85;
                self.tipLabel.text = @"系统评判结果";
                
            } else {
                self.resultLabel.text = @"不合格";
                self.resultLabel.backgroundColor = [UIColor colorWithHex:0xea4f0c];
                self.resultLabel.y = 10;
                self.tipLabel.y = 85;
                self.tipLabel.text = @"系统评判结果";
            }
        }];
        self.scrollView.userInteractionEnabled = YES;
        [self senReadAction:self.senReadBtn];
        [self senReadAction:self.senReadBtn];
        self.pasueState = 1;
    }
}

//暂停后清理子视图
- (void)clearSubView {
    [self.titleBarView removeFromSuperview];
    self.titleBarView = nil;
    
    [self.scrollView removeFromSuperview];
    self.scrollView = nil;
    
    [self.tipsView removeFromSuperview];
    self.tipsView = nil;
    
    [self.tipLabel removeFromSuperview];
    self.tipLabel = nil;
    
    [self.indicatorView removeFromSuperview];
    self.indicatorView = nil;
    
    [self.recordView removeFromSuperview];
    self.recordView = nil;
    
    [self.volumeView removeFromSuperview];
    [self.volumeView freeSource];
    self.volumeView = nil;
    
    [self.evaluatingView removeFromSuperview];
    self.evaluatingView = nil;
}

- (void)stopClickNextBtn {
    [self.nextBtn.button setTitle:@"没有更多" forState:UIControlStateNormal] ;
    self.nextBtn.button.backgroundColor = [UIColor colorWithHex:0xe1e2e2];
    self.nextBtn.enabled = NO;
    _isNoMore = YES;
}

@end
